<?php


namespace app\library\traits;


use app\core\exception\ApiException;
use app\model\Model;
use think\response\Json;

trait CommonController
{
    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];
    /**
     * 模型对象
     * @var Model
     */
    protected $model = null;

    /**
     * 是否开启Validate验证
     */
    protected $modelValidate = false;

    /**
     * 前台提交过来,需要排除的字段数据
     */
    protected $excludeFields = "";


    protected $page;
    protected $count;
    protected $from;

    /**
     * @return Json
     */
    public function index()
    {
        return showSuccess($this->model->list());
    }

    /**
     * @return Json
     * @throws ApiException
     */
    public function save()
    {
        $this->model->saveRow() || error("保存" . $this->model->noticeName . "失败");
        return showSuccessWithMessage("保存" . $this->model->noticeName . "成功");
    }

    /**
     * 更新一条信息
     * @param $id
     * @return Json
     * @throws ApiException
     */
    public function edit($id)
    {
        $this->model->updateRow($id) || error("更新" . $this->model->noticeName . "失败");
        return showSuccessWithMessage("保存" . $this->model->noticeName . "成功");
    }

    /**
     * 读取一条数据
     * @param $id
     * @return array|\think\Model|null
     * @throws ApiException
     */
    public function read($id)
    {
        return $this->model->getOne($id);
    }

    /**
     * 删除一条信息
     * @param $id
     * @return Json
     * @throws ApiException
     */
    public function delete($id)
    {
        $this->model->deleteOne($id) || error("删除" . $this->model->noticeName . "失败");
        return showSuccessWithMessage("删除" . $this->model->noticeName . "成功");
    }
}